﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using HU8.Web.FileExplorer.FileExplorer.Config;
using System.Xml;
using HU8.Helpers.Files;
using System.Web.UI;
using System.Configuration;

namespace HU8.Web.FileExplorer
{
    /// <summary>
    /// 配置文件读取设置
    /// This class is used to read configuration data from Config/config.xml
    /// </summary>
    public class FileExplorerConfig 
    {
        private XmlDocument xml;
        private string configPath;
        private string basePath;
        private Dictionary<string, string> languages;
        private LanguageDictionary lang;
        private string subPath = "";
        HttpContext Context = null;
        string sub_path="";
        public FileExplorerConfig(HttpServerUtility server,HttpContext context)
        {
            Context = context;
           
            configPath = server.MapPath(ConfigurationManager.AppSettings.Get("FileExplorerPath") + "/Config/config.xml");
            basePath = server.MapPath("~/");
            xml = new XmlDocument();
            xml.Load(configPath);

            //缩略图设置
            ThumbConfig = new ThumConfig();
            ThumbConfig.ThumbPath = getSingleNodeAttribute("//FileExplorer/SystemConfig/Thumb", "path");
            ThumbConfig.Enabled = Convert.ToBoolean(getSingleNodeAttribute("//FileExplorer/SystemConfig/Thumb", "enabled"));
            ThumbConfig.Width = Convert.ToInt16(getSingleNodeAttribute("//FileExplorer/SystemConfig/Thumb", "width"));
            ThumbConfig.Height = Convert.ToInt16(getSingleNodeAttribute("//FileExplorer/SystemConfig/Thumb", "height"));
            ThumbConfig.JpegQuality = Convert.ToInt16(getSingleNodeAttribute("//FileExplorer/SystemConfig/Thumb", "jpegQuality"));
            ThumbConfig.PngColorDepth = Convert.ToInt16(getSingleNodeAttribute("//FileExplorer/SystemConfig/Thumb", "pngCompressionLevel"));
            ThumbConfig.PngCompressionLevel = Convert.ToInt16(getSingleNodeAttribute("//FileExplorer/SystemConfig/Thumb", "pngColorDepth"));

            //保护目录设置
            ProtectedPaths = new List<ProtectedPath>();
            foreach (XmlNode n in xml.SelectNodes("//FileExplorer/ProtectedPaths/Path"))
            {
                ProtectedPath p = new ProtectedPath();
                p.RelativePath = n.Attributes["relativePath"].Value.Trim();
                p.Roles = n.Attributes["overrideRoles"].Value.Trim();
                p.AllowRead = Convert.ToBoolean(n.Attributes["read"].Value);
                p.AllowWrite = Convert.ToBoolean(n.Attributes["write"].Value);
                p.AllowDelete = Convert.ToBoolean(n.Attributes["delete"].Value);
                ProtectedPaths.Add(p);
            }

            //现有的语言列表
            languages = new Dictionary<string, string>();
            foreach (XmlNode n in xml.SelectNodes("//Languages/add"))
            {
                string key = n.Attributes["key"].Value.Trim(); ;
                string value = n.Attributes["value"].Value.Trim(); ;
                languages.Add(key, value);
            }

            //必须可读写的目录设置
            EditablePaths = new List<string>();
            foreach (XmlNode n in xml.SelectNodes("//FileExplorer/EditablePaths/Path"))
            {
                string p = n.Attributes["relativePath"].Value;
                EditablePaths.Add(p);
            }

            //Load Language
            lang = new LanguageDictionary(Language, server);
        }

        public string SubPath
        {
            get
            {
                bool b = false;
                if (Context != null)
                {
                    if (Context.Session != null)
                    {
                        if (Context.Session["sub_path"] != null)
                        {
                            subPath = Context.Session["sub_path"].ToString();
                            b = true;
                        }
                    }
                    if (!b)
                    {
                        if (Context.Request != null && Context.Request.Cookies != null && Context.Request.Cookies["sub_path"] != null)
                        {
                            string subPath = Context.Request.Cookies["sub_path"].Value;
                            Context.Session["sub_path"] = subPath;
                            b = true;
                        }
                    }
                }
                if (!b)
                {
                    //sub_path 在 FileService.axms 里面赋值（fileservice 不仅传递cookie 还直接赋值 ，双保险）
                    subPath = sub_path;
                }
                return subPath;
            }
            set
            {
                subPath = value;
            }
        }

        /// <summary>
        /// 语言选择框
        /// </summary>
        /// <returns></returns>
        public string LanguageSelectBox()
        {
            string html = "<select class='fm-language-select-box'>";
            foreach (var i in languages)
            {
                html += string.Format("<option value='{0}' {2}>{1}</option>", i.Key, i.Value, Language == i.Key ? "selected='selected'" : "");
            } html += "</select>";
            return html;
        }

        public string FileExplorerPath { get { return ConfigurationManager.AppSettings.Get("FileExplorerPath"); } }


        /// <summary>
        /// 获取被保护的文件夹
        /// </summary>
        /// <returns></returns>
        public string GetProtectedPaths()
        {
            string result = "<ul>";
            foreach (ProtectedPath p in ProtectedPaths)
            {
                result += string.Format("<li><span class='path'>\"{0}\"</span> [{1}{2}{3}]</li>", p.RelativePath, p.AllowRead?"r":"-", p.AllowWrite?"w":"-", p.AllowDelete?"x":"-");
            }
            result += "</ul>";
            return result;
        }

        /// <summary>
        /// 获取系统属性
        /// </summary>
        /// <returns></returns>
        public string GetSystemVariables()
        {
            string result = "<ul>";
            string dotNetVersionNo = Environment.Version.ToString();
            result += string.Format("<li><label>{1}</label> .Net Framework {0}</li>", dotNetVersionNo, lang.Get("DOT_NET_VERSION"));
            result += string.Format("<li><label>{1}</label>{0}</li>", Environment.UserDomainName, lang.Get("USER_DOMAIN"));
            result += string.Format("<li><label>{1}</label>{0}</li>", Environment.UserName, lang.Get("USER_NAME"));
            result += string.Format("<li><label>{1}</label>{0}</li>", Environment.SystemDirectory, lang.Get("SYSTEM_DIRECTORY"));
            result += string.Format("<li><label>{1}</label>{0}</li>", Environment.OSVersion, lang.Get("OS_VERSION"));
            result += string.Format("<li><label>{1}</label>{0}</li>", Environment.Is64BitProcess ? lang.Get("YES") : lang.Get("NO"), lang.Get("IS_64BIT"));
            result += string.Format("<li><label>{1}</label>{0}</li>", Environment.Is64BitOperatingSystem ? lang.Get("YES") : lang.Get("NO"), lang.Get("IS_64BIT_OS"));
            result += string.Format("<li><label>{1}</label>{0}</li>", Environment.CurrentDirectory, lang.Get("CURRENT_DIRECTORY"));
            result += "</ul>";
            return result;
        }

        public string TestEditablePaths()
        {
            string result = "<ul>";
            foreach (string path in EditablePaths)
            {
                string p = path.Replace("~/", basePath).Replace("/", "\\"); //转换为系统文件路径
                if (FileHelper.CheckSystemPath(p))
                {
                    result += string.Format("<li><label>{1}</label>\"{0}\" {2}</li>", path, lang.Get("SUCCESS"), lang.Get("IS_WRITABLE"));
                }
                else
                {
                    try
                    {
                        FileHelper.SetPermission(p, true, true);
                    }
                    catch (Exception ex)
                    {
                    }
                    if (FileHelper.CheckSystemPath(p))
                    {
                        result += string.Format("<li><label>{1}</label>\"{0}\" {2}</li>", path, lang.Get("SUCCESS"), lang.Get("IS_WRITABLE_AFTER"));
                    }
                    else
                    {
                        result += string.Format("<li><label>{1}</label>\"{0}\" {2}</li>", path, lang.Get("FAILED"), lang.Get("IS_NOT_WRITABLE"));
                    }
                }
            }
            result += "</ul>";
            return result;
        }

        private string getSingleNodeAttribute(string xpath, string attrName)
        {
            XmlNode node = xml.SelectSingleNode(xpath);
            if (node != null)
            {
                return node.Attributes[attrName].Value;
            }
            else
            {
                return "";
            }
        }

        private void setSingleNodeAttribute(string xpath, string attrName, string value)
        {
            XmlNode node = xml.SelectSingleNode(xpath);
            if (node != null)
            {
                node.Attributes[attrName].Value = value;
            }
        }

        public string Title
        {
            get
            {
                return getSingleNodeAttribute("//FileExplorer", "title");
            }
            set
            {
                setSingleNodeAttribute("//FileExplorer", "title", value);
            }
        }

        /// <summary>
        /// 软件版本
        /// </summary>
        public string Version
        {
            get
            {
                return getSingleNodeAttribute("//FileExplorer", "version");
            }
            set
            {
                setSingleNodeAttribute("//FileExplorer", "version", value);
            }
        }

        /// <summary>
        /// 软件语言
        /// </summary>
        public string Language
        {
            get
            {
                return getSingleNodeAttribute("//FileExplorer", "lang");
            }
            set
            {
                setSingleNodeAttribute("//FileExplorer", "lang", value);
            }
        }
        
        /// <summary>
        /// 基础路径
        /// </summary>
        public string BasePath
        {
            get
            {
                string basePath = getSingleNodeAttribute("//FileExplorer/SystemConfig/Base", "path");
                return basePath.EndsWith("/") ? basePath : basePath + "/";
            }
            set
            {
                setSingleNodeAttribute("//FileExplorer/SystemConfig/Base", "path", value);
            }
        }
        /// <summary>
        /// 文件存储路径
        /// </summary>
        public string FilesPath
        {
            get
            {
                string basePath = getSingleNodeAttribute("//FileExplorer/SystemConfig/Files", "path");
                return (basePath.EndsWith("/") ? basePath : basePath + "/")+SubPath;
            }
            set
            {
                setSingleNodeAttribute("//FileExplorer/SystemConfig/Files", "path", value);
            }
        }

        /// <summary>
        /// 文件存储路径 parent_dir + foler_name
        /// </summary>
        //public string SubPath
        //{
        //    get
        //    {

        //        if (Context != null)
        //        {
        //            if (Context.Request != null)
        //            {
        //                if (Context.Request.Cookies["path"] != null)
        //                {
        //                    subPath = Context.Request.Cookies["path"].Value;
        //                }
        //            }
        //        }
                

        //        return subPath;
        //    }
           
        //}

        /// <summary>
        /// 文件存储主目录
        /// </summary>
        public string MainPath
        {
            get
            {
                string basePath = getSingleNodeAttribute("//FileExplorer/SystemConfig/Files", "path");
                return (basePath.EndsWith("/") ? basePath : basePath + "/");
            }
            set
            {
                setSingleNodeAttribute("//FileExplorer/SystemConfig/Files", "path", value);
            }
        }
        /// <summary>
        /// 访问权限
        /// </summary>
        public string AccessRoles
        {
            get
            {
                return getSingleNodeAttribute("//FileExplorer/SystemConfig/Base", "roles");
            }
            set
            {
                setSingleNodeAttribute("//FileExplorer/SystemConfig/Base", "roles", value);
            }
        }

        /// <summary>
        /// 临时文件夹
        /// </summary>
        public string TempPath
        {
            get
            {
                return getSingleNodeAttribute("//FileExplorer/SystemConfig/Temp", "path");
            }
            set
            {
                setSingleNodeAttribute("//FileExplorer/SystemConfig/Temp", "path", value);
            }
        }

        /// <summary>
        /// 多少秒清理一次临时文件夹
        /// </summary>
        public long TempSecondsToClear
        {
            get
            {
                return Convert.ToInt64(getSingleNodeAttribute("//WebServices/PlupLoadThum", "secondsToClear"));
            }
            set
            {
                setSingleNodeAttribute("//WebServices/PlupLoadThum", "secondsToClear", value.ToString());
            }
        }

        public ThumConfig ThumbConfig { get; set; }
        public List<ProtectedPath> ProtectedPaths { get; set; }
        public List<string> EditablePaths { get; set; }


        /// <summary>
        /// TODO: Save configuration alterations to path
        /// 保存Config到文件
        /// </summary>
        public void Save()
        {
            xml.Save(configPath);
        }
    }
}